package com.heba.greenmulu.user;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import com.heba.ATApp;
import com.heba.Cfg;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.GuideActivity;
import com.heba.greenmulu.R;

/**
 * 改变语言
 * <p>
 * Created by jason on 2019/2/12.
 */

public class UserLanguageActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout linear_english;
    private LinearLayout linear_chinese;

    private int lan = 0;    //用于判断是否改变了语言，避免一按返回键就重启应用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_language);
        initTopbar();
        findViewById();
        initView();
    }

    @Override
    protected void findViewById() {
        linear_chinese = findViewById(R.id.linear_chinese);
        linear_english = findViewById(R.id.linear_english);

        linear_chinese.setOnClickListener(this);
        linear_english.setOnClickListener(this);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.language));

        lan = Cfg.Language;
        switch (Cfg.Language) {
            case 1:
                linear_chinese.setSelected(false);
                linear_english.setSelected(true);
                break;
            case 2:
                linear_chinese.setSelected(true);
                linear_english.setSelected(false);
                break;
            default:
                linear_chinese.setSelected(false);
                linear_english.setSelected(false);
        }

        img_back.setOnClickListener(v -> changeLanguage());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.linear_chinese:
                linear_chinese.setSelected(true);
                linear_english.setSelected(false);
                Cfg.change("Language", 2);
                break;
            case R.id.linear_english:
                linear_chinese.setSelected(false);
                linear_english.setSelected(true);
                Cfg.change("Language", 1);
                break;
            default:
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        changeLanguage();
    }

    /**
     * 改变语言
     */
    private void changeLanguage() {
        if (Cfg.Language != lan) {
            //改变了语言，重启应用
            Cfg.save();   //保存語言
            ATApp.setAppLanguage();  //更新語言
            ATApp.updateRefreshContent();  //更新刷新框架語言
            finish();
            Intent intent = new Intent(this, GuideActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        } else {
            finishActivity();
        }
    }
}
